import './utils/os'

import { BrowserWindow, app, ipcMain, shell } from 'electron'
import {
  batchActiveCustomFonts,
  getRegisteredFonts,
  loadCustomFont,
  removeCustomFont,
  switchFontfamily
} from './utils/customFonts'
import {
  customStoragePath,
  getUserFilesStoragePath,
  openStoragePath,
  showItemInFolder
} from './utils/customStoragePath'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import {
  getFilePathFromProcessArgv,
  getRevezoneLinkFromCommandLine,
  onAddFile,
  onDeleteFileOrFolder,
  onDragAndDrop,
  onFileDataChange,
  onRenameFileOrFolder
} from './utils/localFilesStorage'

import { EVENTS } from '../preload/events'
import Store from 'electron-store'
import fs from 'node:fs'
import { isMacOS } from './utils/platform'
import { join } from 'path'
import { notify } from './utils/notification'
import { registerAppMenu } from './utils/menu'

const DEFAULT_WINDOW_WIDTH = 1200
const DEFAULT_WINDOW_HEIGHT = 770

// 创建一个新的存储实例
const store = new Store()

let mainWindow

// IMPORTANT: to fix file save problem in excalidraw: The request is not allowed by the user agent or the platform in the current context
app.commandLine.appendSwitch('enable-experimental-web-platform-features')

app.setAsDefaultProtocolClient('revezone')
function createWindow() {
  if (mainWindow) return mainWindow

  const savedSize = store.get('windowSize', {
    width: DEFAULT_WINDOW_WIDTH,
    height: DEFAULT_WINDOW_HEIGHT
  })

  // Create the browser window.
  mainWindow = new BrowserWindow({
    titleBarStyle: isMacOS() ? 'hiddenInset' : 'default',
    titleBarOverlay: isMacOS() ? false : true,
    width: savedSize.width,
    height: savedSize.height,
    show: false,
    frame: true,
    trafficLightPosition: { x: 10, y: 10 },
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false
    }
  })

  registerAppMenu()

  getRegisteredFonts()
  // batchActiveCustomFonts(mainWindow)

  process.env['USER_FILES_STORAGE_PATH'] = getUserFilesStoragePath()

  mainWindow.setMenuBarVisibility(false)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // Protocol handler for win32
  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments

    const deeplinkingUrl = getRevezoneLinkFromCommandLine(process.argv)

    process.env.DEEP_LINKING_URL = deeplinkingUrl

    notify(process.argv.join(', '))

    const filePath = getFilePathFromProcessArgv(process.argv)

    process.env.OPEN_FILE_PATH = filePath

    const fileData = fs.readFileSync(filePath).toString()

    process.env.OPEN_FILE_DATA = fileData
  }

  mainWindow.on('closed', () => {
    mainWindow?.removeAllListeners()
    mainWindow = null
    ipcMain.removeAllListeners()
  })

  mainWindow.on('resize', () => {
    const [width, height] = mainWindow?.getSize() || [DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT]

    store.set('windowSize', { width, height })
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // mainWindow.webContents.openDevTools()

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  if (isMacOS()) {
    ipcMain.on(EVENTS.toggleTrafficLight, (event, isShow) => {
      mainWindow?.setWindowButtonVisibility(isShow)
    })
  }

  ipcMain.on(EVENTS.loadCustomFont, async () => {
    mainWindow && loadCustomFont(mainWindow)
  })

  ipcMain.on(EVENTS.removeCustomFont, async (event, fontPath) => {
    mainWindow && removeCustomFont(fontPath, mainWindow)
  })

  ipcMain.on(EVENTS.switchFontfamily, async (event, fontName) => {
    mainWindow && switchFontfamily(mainWindow, fontName)
  })

  ipcMain.on(EVENTS.addFile, (event, fileId, value, fileTree) => {
    onAddFile(fileId, value, fileTree)
  })

  ipcMain.on(EVENTS.fileDataChange, async (event, fileId, value, fileTree) => {
    onFileDataChange(fileId, value, fileTree)
  })

  ipcMain.on(EVENTS.renameFileOrFolder, async (event, fileId, newName, fileTree) => {
    onRenameFileOrFolder(fileId, newName, fileTree)
  })

  ipcMain.on(EVENTS.deleteFileOrFolder, async (event, item, fileTree) => {
    onDeleteFileOrFolder(item, fileTree)
  })

  ipcMain.on(EVENTS.customStoragePath, async () => {
    mainWindow && customStoragePath(mainWindow)
  })

  ipcMain.on(EVENTS.openStoragePath, async (event, storagePath) => {
    openStoragePath(storagePath)
  })

  ipcMain.on(EVENTS.showItemInFolder, async (event, itemId, fileTree) => {
    mainWindow && showItemInFolder(itemId, fileTree)
  })

  ipcMain.on(EVENTS.dragAndDrop, async (event, items, parentId, fileTree) => {
    onDragAndDrop(items, parentId, fileTree)
  })

  return mainWindow
}

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  // For Windows
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // console.log('second instance', commandLine, workingDirectory)
    // console.log('process.argv', process.argv)

    // notify(commandLine?.join(', '))
    // notify(process.argv.join(', '))

    // Someone tried to run a second instance, we should focus our window.
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      setTimeout(() => {
        const link = getRevezoneLinkFromCommandLine(commandLine)
        link && mainWindow?.webContents.send(EVENTS.openRevezoneLinkSuccess, link)
      }, 500)
    }
  })
}

// For Mac OS Only
app.on('open-file', (event, path) => {
  event.preventDefault()

  console.log('open file: ', path)

  const fileData = fs.readFileSync(path).toString()

  let _mainWindow = mainWindow

  if (BrowserWindow.getAllWindows().length === 0) {
    app.whenReady().then(() => {
      _mainWindow = createWindow()
      _mainWindow.webContents.on('did-finish-load', () => {
        setTimeout(() => {
          mainWindow?.webContents.send(EVENTS.openFileSuccess, path, fileData)
        }, 500)
      })
    })
  } else {
    mainWindow?.webContents.send(EVENTS.openFileSuccess, path, fileData)
  }
})

// For Mac OS Only
app.on('open-url', (event, link) => {
  event.preventDefault()

  console.log('open-url', link)

  process.env.DEEP_LINKING_URL = link

  let _mainWindow = mainWindow

  if (BrowserWindow.getAllWindows().length === 0) {
    app.whenReady().then(() => {
      _mainWindow = createWindow()
    })
  } else {
    _mainWindow?.webContents.send(EVENTS.openRevezoneLinkSuccess, link)
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
